<template>
	<view class="mv-container">
		<musichead class="mv-musichead" name="视频" :isShowback="true" />
		<view class="video-container">
			<view class="video-wrapper" v-if="videos.length > 0">
				<video 
					:id="'video-' + currentIndex"
					:ref="'video-' + currentIndex"
					class="video-player"
					:src="videos[currentIndex].url"
					:poster="videos[currentIndex].poster"
					:loop="true"
					:muted="isMuted"
					:show-center-play-btn="false"
					:controls="false"
					:enable-progress-gesture="false"
					:object-fit="'contain'"
					@ended="handleVideoEnd"
					@error="handleVideoError">
				</video>
				<view class="video-controls" @tap="handleVideoTap">
					<text v-if="!isPlaying" 
						class="iconfont icon-zanting2 play-icon"></text>
					<!-- Sound control button -->
					<view class="sound-control" @tap.stop="toggleSound">
						<text class="iconfont" :class="isMuted ? 'icon-jingyin' : 'icon-sound'"></text>
					</view>
				</view>
				<view class="video-info">
					<text class="video-title">{{ videos[currentIndex].title || '视频标题' }}</text>
				</view>
				<!-- Initial play overlay -->
				<view v-if="!hasInteracted" class="initial-play-overlay" @tap="handleFirstInteraction">
					<text class="play-text">点击开始播放</text>
				</view>
			</view>
			
			<!-- Navigation buttons -->
			<view class="nav-buttons">
				<view class="nav-btn prev-btn" @tap="goToPrevious" :class="{ disabled: currentIndex === 0 }">
					<text class="iconfont icon-shangyige"></text>
				</view>
				<view class="nav-btn next-btn" @tap="goToNext">
					<text class="iconfont icon-xiayige"></text>
				</view>
			</view>
			
			<!-- Video indicator -->
			<view class="video-indicator">
				<text class="indicator-text">{{ currentIndex + 1 }} / {{ videos.length }}</text>
			</view>
		</view>
	</view>
</template>

<script>
	import musichead from '../../components/musichead/musichead.vue'
	import { getMVUrl, getMVId } from '../../common/api'

	export default {
		components: {
			musichead
		},
		data() {
			return {
				videos: [],
				currentIndex: 0,
				isPlaying: false,
				currentVideo: null,
				preloadLimit: 2, // Number of videos to preload ahead
				isMuted: true, // Start muted to allow autoplay
				hasInteracted: false, // Track if user has interacted
				platform: '', // Platform detection
				isLoading: false // Prevent multiple loading operations
			}
		},
		async onLoad() {
			// Detect platform
			// #ifdef H5
			this.platform = 'h5'
			// #endif
			
			// #ifdef APP-PLUS
			this.platform = 'app'
			this.hasInteracted = true // No restrictions on app
			this.isMuted = false
			// #endif
			
			// Initial load of videos
			await this.loadInitialVideos()
		},
		methods: {
			async loadInitialVideos() {
				try {
					this.isLoading = true
					// Load initial set of videos
					for (let i = 0; i < 3; i++) {
						await this.addNewVideo()
					}
					
					// Start playing the first video after a short delay
					setTimeout(() => {
						if (this.platform === 'h5' && !this.hasInteracted) {
							// On H5, wait for user interaction
							this.isPlaying = false
						} else {
							this.playCurrentVideo()
						}
					}, 500)
				} catch (error) {
					console.error('Failed to load initial videos:', error)
					uni.showToast({
						title: '视频加载失败',
						icon: 'none'
					})
				} finally {
					this.isLoading = false
				}
			},
			
			handleFirstInteraction() {
				this.hasInteracted = true
				this.isMuted = false
				this.playCurrentVideo()
			},
			
			handleVideoTap(e) {
				if (!this.hasInteracted) {
					this.handleFirstInteraction()
				} else {
					this.togglePlay()
				}
			},
			
			toggleSound(e) {
				e.stopPropagation()
				this.isMuted = !this.isMuted
				if (this.currentVideo) {
					if (this.isMuted) {
						this.currentVideo.mute()
					} else {
						this.currentVideo.unmute()
					}
				}
			},
			
			async addNewVideo() {
				try {
					const id = await getMVId()
					const url = await getMVUrl(String(id))
					this.videos.push({
						id: String(id),
						url: url,
						poster: '', // You can add a poster image URL if available
						title: '视频 ' + (this.videos.length + 1)
					})
				} catch (error) {
					console.error('Failed to add new video:', error)
					throw error
				}
			},
			
			async goToPrevious() {
				if (this.currentIndex <= 0 || this.isLoading) return
				
				// Pause current video
				if (this.currentVideo) {
					this.currentVideo.pause()
					this.isPlaying = false
				}
				
				this.currentIndex--
				if (this.hasInteracted || this.platform === 'app') {
					// Small delay to allow DOM update
					setTimeout(() => {
						this.playCurrentVideo()
					}, 100)
				}
			},
			
			async goToNext() {
				if (this.isLoading) return
				
				// Pause current video
				if (this.currentVideo) {
					this.currentVideo.pause()
					this.isPlaying = false
				}
				
				// Check if we need to load more videos
				if (this.currentIndex >= this.videos.length - 1) {
					try {
						this.isLoading = true
						await this.addNewVideo()
					} catch (error) {
						uni.showToast({
							title: '加载下一个视频失败',
							icon: 'none'
						})
						return
					} finally {
						this.isLoading = false
					}
				}
				
				this.currentIndex++
				
				// Preload next videos if needed
				await this.preloadVideos()
				
				if (this.hasInteracted || this.platform === 'app') {
					// Small delay to allow DOM update
					setTimeout(() => {
						this.playCurrentVideo()
					}, 100)
				}
			},
			
			async preloadVideos() {
				const neededVideos = this.currentIndex + this.preloadLimit + 1
				if (this.videos.length < neededVideos && !this.isLoading) {
					try {
						this.isLoading = true
						while (this.videos.length < neededVideos) {
							await this.addNewVideo()
						}
					} catch (error) {
						console.error('Failed to preload videos:', error)
					} finally {
						this.isLoading = false
					}
				}
			},
			
			playCurrentVideo() {
				const videoId = 'video-' + this.currentIndex
				const video = uni.createVideoContext(videoId, this)
				this.currentVideo = video
				
				if (this.platform === 'h5' && !this.hasInteracted) {
					video.mute()
					this.isMuted = true
				}
				
				video.play()
				this.isPlaying = true
			},
			
			togglePlay() {
				if (!this.currentVideo) return
				
				if (this.isPlaying) {
					this.currentVideo.pause()
					this.isPlaying = false
				} else {
					this.currentVideo.play()
					this.isPlaying = true
				}
			},
			
			handleVideoEnd() {
				this.playCurrentVideo()
			},
			
			handleVideoError(err) {
				console.error('Video playback error:', err)
				uni.showToast({
					title: '视频播放出错',
					icon: 'none'
				})
			}
		}
	}
</script>

<style lang="scss">
	.mv-container {
		width: 100vw;
		height: 100vh;
		background-color: #000;
		position: relative;
		
		.mv-musichead {
			position: fixed;
			top: 0;
			left: 0;
			width: 100%;
			z-index: 100;
		}
		
		.video-container {
			width: 100%;
			height: 100%;
			position: relative;
			
			.video-wrapper {
				width: 100%;
				height: 100%;
				position: relative;
				
				.video-player {
					width: 100%;
					height: 100%;
					position: absolute;
				}
				
				.video-controls {
				position: absolute;
					top: 0;
					left: 0;
					width: 100%;
					height: 100%;
					display: flex;
					align-items: center;
					justify-content: center;
					
					.play-icon {
						font-size: 80px;
						color: rgba(255, 255, 255, 0.8);
						background-color: rgba(0, 0, 0, 0.3);
						border-radius: 50%;
						padding: 20px;
					}
					
					.sound-control {
						position: absolute;
						right: 20px;
						bottom: 120px;
						width: 40px;
						height: 40px;
						background-color: rgba(0, 0, 0, 0.5);
						border-radius: 50%;
						display: flex;
						align-items: center;
						justify-content: center;
						
						text {
							color: #fff;
							font-size: 24px;
						}
					}
					}

				.video-info {
						position: absolute;
					bottom: 80px;
					left: 20px;
					right: 20px;
					z-index: 2;
					
					.video-title {
						color: #fff;
						font-size: 16px;
						text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
					}
				}
				
				.initial-play-overlay {
					position: absolute;
					top: 0;
					left: 0;
					width: 100%;
					height: 100%;
					background-color: rgba(0, 0, 0, 0.5);
					display: flex;
					align-items: center;
					justify-content: center;
					z-index: 3;
					
					.play-text {
						color: #fff;
						font-size: 18px;
						padding: 15px 30px;
						background-color: rgba(255, 255, 255, 0.2);
						border-radius: 25px;
					}
				}
			}
			
			.nav-buttons {
				position: absolute;
				top: 50%;
				left: 0;
				right: 0;
				transform: translateY(-50%);
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 0 20px;
				z-index: 10;
				pointer-events: none;
				
				.nav-btn {
					width: 50px;
					height: 50px;
					background-color: rgba(0, 0, 0, 0.6);
					border-radius: 50%;
					display: flex;
					align-items: center;
					justify-content: center;
					pointer-events: auto;
					transition: all 0.3s ease;
					
					text {
						color: #fff;
						font-size: 24px;
					}
					
					&:active {
						transform: scale(0.9);
						background-color: rgba(0, 0, 0, 0.8);
					}
					
					&.disabled {
						opacity: 0.3;
						pointer-events: none;
					}
				}
				
				.prev-btn {
					left: 20px;
				}
				
				.next-btn {
					right: 20px;
				}
			}
			
			.video-indicator {
				position: absolute;
				top: 100px;
				right: 20px;
				background-color: rgba(0, 0, 0, 0.5);
				padding: 8px 12px;
				border-radius: 15px;
				z-index: 10;
				
				.indicator-text {
					color: #fff;
					font-size: 14px;
				}
			}
		}
	}
</style>